package jok.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyByteDemo {
	public static void main(String[] args) {
		File file = new File("D:/aa");
		if (!file.exists())
			file.mkdir();

		FileWriterDemo.writeFile3();

		// fileCopy();
		// fileCopy2();
		fileCopy3();

		FileDemo.deleteFile("D:/aa");
		FileDemo.deleteFile("D:/a.txt");
	}

	/**
	 * 使用字节流 单个字符 形式复制文件
	 */
	public static void fileCopy() {
		FileOutputStream fos = null;
		FileInputStream fis = null;

		try {
			fos = new FileOutputStream("D:/aa/a.txt");
			fis = new FileInputStream("D:/a.txt");

			int num = -1;
			while ((num = fis.read()) != -1) {
				fos.write(num);
			}
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用字节流 字符数组 形式复制文件
	 */
	public static void fileCopy2() {
		FileOutputStream fos = null;
		FileInputStream fis = null;

		try {
			fos = new FileOutputStream("D:/aa/a.txt");
			fis = new FileInputStream("D:/a.txt");

			byte[] bs = new byte[1024];
			int num = -1;
			while ((num = fis.read(bs)) != -1) {
				fos.write(bs, 0, num);
			}
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用 高速缓冲字节流 字符数组 形式复制文件
	 */
	public static void fileCopy3() {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;

		try {
			bos = new BufferedOutputStream(new FileOutputStream("D:/aa/a.txt"));
			bis = new BufferedInputStream(new FileInputStream("D:/a.txt"));

			byte[] cs = new byte[1024];
			int num = -1;
			while ((num = bis.read(cs)) != -1) {
				bos.write(cs, 0, num);
				bos.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
